package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;
import java.util.Random;

public class BookAdapter extends BaseAdapter {
    private Context context;
    private List<Book> bookList;
    TextView bookTitleTextView;
    TextView bookAuthorTextView ;
    TextView bookDescriptionTextView;
    private static final int[] BOOK_IMAGES = {
            R.drawable.j,
            R.drawable.aa,
            R.drawable.bb,
            R.drawable.cc,
            R.drawable.dd
    };
    public BookAdapter(Context context, List<Book> bookList) {
        this.context = context;
        this.bookList = bookList;
    }

    @Override
    public int getCount() {
        return bookList.size();
    }

    @Override
    public Object getItem(int position) {
        return bookList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return bookList.get(position).getId();
    }
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.books_list_layout, parent, false);
        }

        Book book = bookList.get(position);

        // 设置随机图片
        ImageView bookImageView = convertView.findViewById(R.id.bookImageView);
        Random random = new Random();
        int randomImageIndex = random.nextInt(BOOK_IMAGES.length);
        bookImageView.setImageResource(BOOK_IMAGES[randomImageIndex]);

        // 设置文本
        bookTitleTextView = convertView.findViewById(R.id.bookTitleTextView);
        bookAuthorTextView = convertView.findViewById(R.id.bookAuthorTextView);
        bookDescriptionTextView = convertView.findViewById(R.id.bookDescriptionTextView);

        bookTitleTextView.setText("书名：" + book.getTitle());
        bookAuthorTextView.setText("作者：" + book.getAuthor());
        bookDescriptionTextView.setText("简介：" + book.getRemark());

        return convertView;
    }
}
